import React, { useState } from 'react';
import { Typography, Card, Form, Input, Select, Button, Steps, Space, Alert, Radio } from 'antd';
import { SafetyCertificateOutlined, CloudOutlined, GlobalOutlined } from '@ant-design/icons';

const { Title, Text } = Typography;
const { Option } = Select;

interface CertificateFormData {
  domain: string;
  provider: string;
  email: string;
  validation_method: 'dns' | 'http';
  auto_deploy: boolean;
}

const CertificateApply: React.FC = () => {
  const [form] = Form.useForm<CertificateFormData>();
  const [currentStep, setCurrentStep] = useState(0);
  const [loading, setLoading] = useState(false);

  const providers = [
    { value: 'letsencrypt', label: "Let's Encrypt", free: true },
    { value: 'zerossl', label: 'ZeroSSL', free: true },
    { value: 'aliyun', label: '阿里云SSL', free: false },
    { value: 'tencent', label: '腾讯云SSL', free: false },
    { value: 'google', label: 'Google Trust Services', free: true },
  ];

  const steps = [
    {
      title: '选择域名',
      description: '输入需要申请证书的域名',
    },
    {
      title: '选择CA机构',
      description: '选择证书颁发机构',
    },
    {
      title: '验证配置',
      description: '配置域名验证方式',
    },
    {
      title: '提交申请',
      description: '确认信息并提交申请',
    },
  ];

  const handleNext = async () => {
    try {
      await form.validateFields();
      setCurrentStep(currentStep + 1);
    } catch (error) {
      console.error('表单验证失败:', error);
    }
  };

  const handlePrev = () => {
    setCurrentStep(currentStep - 1);
  };

  const handleSubmit = async () => {
    try {
      setLoading(true);
      const values = await form.validateFields();
      console.log('提交证书申请:', values);
      // 这里可以调用API提交申请
      
      // 模拟API调用
      setTimeout(() => {
        setLoading(false);
        alert('证书申请已提交，请等待审核！');
        setCurrentStep(0);
        form.resetFields();
      }, 2000);
    } catch (error) {
      console.error('提交失败:', error);
      setLoading(false);
    }
  };

  const renderStepContent = () => {
    switch (currentStep) {
      case 0:
        return (
          <Card>
            <Form.Item
              name="domain"
              label="域名"
              rules={[
                { required: true, message: '请输入域名' },
                { pattern: /^([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/, message: '请输入有效的域名' }
              ]}
            >
              <Input
                prefix={<GlobalOutlined />}
                placeholder="例如: example.com 或 *.example.com"
                size="large"
              />
            </Form.Item>
            <Alert
              message="支持单域名和通配符域名"
              description="单域名证书仅对指定域名有效，通配符证书对子域名也有效"
              type="info"
              showIcon
              style={{ marginTop: 16 }}
            />
          </Card>
        );

      case 1:
        return (
          <Card>
            <Form.Item
              name="provider"
              label="CA机构"
              rules={[{ required: true, message: '请选择CA机构' }]}
            >
              <Radio.Group>
                <Space direction="vertical" style={{ width: '100%' }}>
                  {providers.map(provider => (
                    <Radio key={provider.value} value={provider.value}>
                      <Space>
                        <Text strong>{provider.label}</Text>
                        {provider.free && (
                          <Text type="success" style={{ fontSize: 12 }}>免费</Text>
                        )}
                      </Space>
                    </Radio>
                  ))}
                </Space>
              </Radio.Group>
            </Form.Item>
            
            <Form.Item
              name="email"
              label="邮箱地址"
              rules={[
                { required: true, message: '请输入邮箱地址' },
                { type: 'email', message: '请输入有效的邮箱地址' }
              ]}
            >
              <Input placeholder="用于接收证书通知" size="large" />
            </Form.Item>
          </Card>
        );

      case 2:
        return (
          <Card>
            <Form.Item
              name="validation_method"
              label="验证方式"
              rules={[{ required: true, message: '请选择验证方式' }]}
            >
              <Radio.Group>
                <Space direction="vertical">
                  <Radio value="dns">
                    <Space direction="vertical" size={0}>
                      <Text strong>DNS验证</Text>
                      <Text type="secondary" style={{ fontSize: 12 }}>
                        在DNS记录中添加TXT记录进行验证（推荐）
                      </Text>
                    </Space>
                  </Radio>
                  <Radio value="http">
                    <Space direction="vertical" size={0}>
                      <Text strong>HTTP验证</Text>
                      <Text type="secondary" style={{ fontSize: 12 }}>
                        在网站根目录放置验证文件
                      </Text>
                    </Space>
                  </Radio>
                </Space>
              </Radio.Group>
            </Form.Item>

            <Form.Item
              name="auto_deploy"
              label="自动部署"
              valuePropName="checked"
            >
              <Radio.Group>
                <Radio value={true}>启用自动部署到CDN/负载均衡</Radio>
                <Radio value={false}>手动部署</Radio>
              </Radio.Group>
            </Form.Item>
          </Card>
        );

      case 3:
        const values = form.getFieldsValue();
        return (
          <Card>
            <Space direction="vertical" size="middle" style={{ width: '100%' }}>
              <Title level={5}>请确认申请信息：</Title>
              
              <div>
                <Text strong>域名：</Text>
                <Text>{values.domain}</Text>
              </div>
              
              <div>
                <Text strong>CA机构：</Text>
                <Text>{providers.find(p => p.value === values.provider)?.label}</Text>
              </div>
              
              <div>
                <Text strong>邮箱：</Text>
                <Text>{values.email}</Text>
              </div>
              
              <div>
                <Text strong>验证方式：</Text>
                <Text>{values.validation_method === 'dns' ? 'DNS验证' : 'HTTP验证'}</Text>
              </div>
              
              <div>
                <Text strong>自动部署：</Text>
                <Text>{values.auto_deploy ? '已启用' : '已禁用'}</Text>
              </div>

              <Alert
                message="提交后将开始证书申请流程"
                description="证书申请通常需要几分钟到几小时不等，我们会通过邮件通知您申请结果"
                type="warning"
                showIcon
              />
            </Space>
          </Card>
        );

      default:
        return null;
    }
  };

  return (
    <div style={{ padding: '24px' }}>
      <div style={{ marginBottom: '32px' }}>
        <Title level={2} style={{ margin: 0, marginBottom: '8px' }}>
          <SafetyCertificateOutlined style={{ marginRight: '8px', color: '#52c41a' }} />
          申请SSL证书
        </Title>
        <Text type="secondary">
          快速申请免费或付费SSL证书，支持多种CA机构和验证方式
        </Text>
      </div>

      <div style={{ maxWidth: 800, margin: '0 auto' }}>
        <Card style={{ marginBottom: '24px' }}>
          <Steps
            current={currentStep}
            items={steps}
            style={{ marginBottom: '32px' }}
          />

          <Form
            form={form}
            layout="vertical"
            initialValues={{
              provider: 'letsencrypt',
              validation_method: 'dns',
              auto_deploy: false,
            }}
          >
            {renderStepContent()}
          </Form>

          <div style={{ 
            display: 'flex', 
            justifyContent: 'space-between', 
            marginTop: '32px',
            paddingTop: '24px',
            borderTop: '1px solid #f0f0f0'
          }}>
            <Button
              onClick={handlePrev}
              disabled={currentStep === 0}
            >
              上一步
            </Button>

            <div>
              {currentStep < steps.length - 1 && (
                <Button type="primary" onClick={handleNext}>
                  下一步
                </Button>
              )}
              {currentStep === steps.length - 1 && (
                <Button
                  type="primary"
                  loading={loading}
                  onClick={handleSubmit}
                  icon={<SafetyCertificateOutlined />}
                >
                  提交申请
                </Button>
              )}
            </div>
          </div>
        </Card>
      </div>
    </div>
  );
};

export default CertificateApply; 